//
//  SISSNotificationListViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/6/20.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSNotificationListViewController.h"
#import "SISSNotificationListCell.h"
#import "SISSNetworkingManager+Message.h"
#import "SISSNotiWebViewController.h"
#import "SISSNotificationRecordModel.h"

static NSString *notificationListCellReuseID = @"notificationListCellReuseID";
@interface SISSNotificationListViewController ()<UITableViewDelegate,UITableViewDataSource>

/* tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;

/* 协会公告数组 */
@property (strong, nonatomic) NSArray<SISSNotificationRecordModel *> *notiRecordArr;

@end

@implementation SISSNotificationListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    } // 去除顶部20个距离
    [self requestData];
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf requestData];
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [tableView tableViewDisplayWithMessage:@"暂无数据" ifNecessaryForRowCount:self.notiRecordArr.count];
    return self.notiRecordArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSNotificationListCell *cell = [tableView dequeueReusableCellWithIdentifier:notificationListCellReuseID];
    cell.notificationType = self.notificationType;
    cell.nofiRecordModel = self.notiRecordArr[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SISSNotiWebViewController *vc = [[SISSNotiWebViewController alloc] init];
    vc.title = self.title;
    if (!(self.notiRecordArr[indexPath.section].url.length > 0)) return;
    vc.url = self.notiRecordArr[indexPath.section].url;
    [self.navigationController pushViewController:vc animated:YES];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}

// 分区头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 16 / 375.0 * SCREEN_WIDTH;
}


#pragma mark - 获取数据
- (void)requestData {
    
    if (self.notificationType == SISSNotificationTypeNoticeRecord) {
        [self requestNoticeRecordData];
    } else if (self.notificationType == SISSNotificationTypeSystemMessage) {
        [self requestSystemMessageData];
    }
}

#pragma mark -- 获取协会公告数据
- (void)requestNoticeRecordData {
    
    WeakSelf
    [kNetworkManager requestNoticeRecordWithSuccess:^(NSArray<SISSNotificationRecordModel *> *notiRecordArr) {
        
        weakSelf.notiRecordArr = notiRecordArr;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}

#pragma mark -- 获取系统消息数据
- (void)requestSystemMessageData {
    
    WeakSelf
    [kNetworkManager requestSystemMessageWithSuccess:^(NSArray<SISSNotificationRecordModel *> *systemMessageArr) {
        
        weakSelf.notiRecordArr = systemMessageArr;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 清空系统通知
- (void)clearSystemMessageData {
    
    WeakSelf
    [kNetworkManager clearSystemMessageWithSuccess:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 清空成功
        
            [weakSelf requestSystemMessageData];
        }
        
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - 清空按钮点击事件
- (void)clickEmptyItemAction {
    
    NSString *str = self.notiRecordArr.count > 0 ? @"清空后不可恢复，您确定要清空吗？" : @"您已清空所有系统消息！";
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str attributes:
                                       @{
                                         NSFontAttributeName : [UIFont systemFontOfSize:13],
                                         NSForegroundColorAttributeName: COLOR(0x334A60),
                                         NSParagraphStyleAttributeName: paragraphStyle
                                         }];
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"清空" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alertC setValue:attr forKey:@"attributedMessage"];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    [alertC addAction:cancelAction];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (self.notiRecordArr.count > 0) {
            [self clearSystemMessageData];
        }
        
        NSLog(@"确定");
    }];
    [alertC addAction:okAction];
    
    [self presentViewController:alertC animated:YES completion:nil];
}

#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    [tableView registerClass:[SISSNotificationListCell class] forCellReuseIdentifier:notificationListCellReuseID];
    tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 自动布局
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark - NavigationItem
- (void)setupNavigationItems {
    [super setupNavigationItems];
    
    self.navigationItem.rightBarButtonItem = self.notificationType == SISSNotificationTypeSystemMessage ? [[UIBarButtonItem alloc] initWithTitle:@"清空" style:UIBarButtonItemStylePlain target:self action:@selector(clickEmptyItemAction)] : nil;
}

@end
